﻿{extend name="public:base" /}

{block name="css"}
<link href="/static/bootstrap/css/bootstrap-table.min.css" rel="stylesheet">
<link rel="stylesheet" href="__PLUG__/jquery-treegrid-master/css/jquery.treegrid.min.css">

<style>
    .fixed-table-body {
        overflow-x: auto;
        overflow-y: auto;
        height: auto;
    }

    .fixed-table-container .bs-checkbox .th-inner {
        padding: 14px 0;
    }

    .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td {
        border-top: 1px solid #e7eaec;
        line-height: 1.42857;
        padding: 8px;
        vertical-align: inherit;
        text-align: revert;
    }
</style>{/block}

{block name="content"}
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox ">
                <div class="ibox-title">
                    <a href="{:url('doCourseCategory')}" class="btn btn-primary btn-lg">新增</a>

                    <div class="ibox-tools">
                        <a class="collapse-link">
                            <i class="iconfont icon-chevron-up"></i>
                        </a>
                    </div>
                </div>

                <div class="ibox-content">
                    <table id="table"></table>
                </div>
            </div>
        </div>
    </div>
</div>{/block}

{block name="js"}
<script src="/static/bootstrap/js/bootstrap-table.min.js"></script>
<script src="__PLUG__/jquery-treegrid-master/examples/bootstrap-table-treegrid.js"></script>
<script src="__PLUG__/jquery-treegrid-master/js/jquery.treegrid.min.js"></script>

<script type="text/javascript">
    var $table = $('#table');
    var data = `{$list_json}` ? JSON.parse(`{$list_json}`) : [];
    console.log(data)
    /*var data = JSON.parse(
      '[{"id":1,"pid":0,"status":1,"name":"用户管理","permissionValue":"open:user:manage"},' +
      '{"id":2,"pid":0,"status":1,"name":"系统管理","permissionValue":"open:system:manage"},' +
      '{"id":3,"pid":1,"status":1,"name":"新增用户","permissionValue":"open:user:add"},' +
      '{"id":4,"pid":1,"status":1,"name":"修改用户","permissionValue":"open:user:edit"},' +
      '{"id":5,"pid":1,"status":0,"name":"删除用户","permissionValue":"open:user:del"},' +
      '{"id":6,"pid":2,"status":1,"name":"系统配置管理","permissionValue":"open:systemconfig:manage"},' +
      '{"id":7,"pid":6,"status":1,"name":"新增配置","permissionValue":"open:systemconfig:add"},' +
      '{"id":8,"pid":6,"status":1,"name":"修改配置","permissionValue":"open:systemconfig:edit"},' +
      '{"id":9,"pid":6,"status":0,"name":"删除配置","permissionValue":"open:systemconfig:del"},' +
      '{"id":10,"pid":2,"status":1,"name":"系统日志管理","permissionValue":"open:log:manage"},' +
      '{"id":11,"pid":10,"status":1,"name":"新增日志","permissionValue":"open:log:add"},' +
      '{"id":12,"pid":10,"status":1,"name":"修改日志","permissionValue":"open:log:edit"},' +
      '{"id":13,"pid":10,"status":0,"name":"删除日志","permissionValue":"open:log:del"}]'
    );*/

    $(function () {

        //控制台输出一下数据
        // console.log(data);
        console.log($table)
        $table.bootstrapTable({
            data: data,
            idField: 'id',
            dataType: 'jsonp',
            columns: [
                // 复选框
                {
                    field: 'check', checkbox: true, formatter: function (value, row, index) {
                        if (row.check == true) {
                            // console.log(row.serverName);
                            //设置选中
                            return {checked: true};
                        }
                    }
                },
                {field: 'name', title: '名称'},
                {field: 'sort', title: '排序'},
                // {field: 'id', title: '编号', sortable: true, align: 'center'},
                // {field: 'pid', title: '所属上级'},
                {field: 'operate', title: '操作', align: 'center', events: operateEvents, formatter: 'operateFormatter'},
            ],

            // bootstrap-table-treegrid.js 插件配置 -- start

            //在哪一列展开树形
            treeShowField: 'name',
            //指定父id列
            parentIdField: 'pid',

            onResetView: function (data) {
                //console.log('load');
                $table.treegrid({
                    // initialState: 'collapsed',// 所有节点都折叠
                    initialState: `{:input('return_top_ids')}` ? 'expanded' : 'collapsed',// 所有节点都展开，默认展开
                    treeColumn: 1,
                    // expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                    // expanderCollapsedClass: 'glyphicon glyphicon-plus',
                    onChange: function () {
                        $table.bootstrapTable('resetWidth');
                    }
                });

                //只展开树形的第一级节点
                // $table.treegrid('getRootNodes').treegrid('expand');

            },
            onCheck: function (row) {
                var datas = $table.bootstrapTable('getData');
                // 勾选子类
                selectChilds(datas, row, "id", "pid", true);

                // 勾选父类
                selectParentChecked(datas, row, "id", "pid")

                // 刷新数据
                $table.bootstrapTable('load', datas);
            },

            onUncheck: function (row) {
                var datas = $table.bootstrapTable('getData');
                selectChilds(datas, row, "id", "pid", false);
                $table.bootstrapTable('load', datas);
            },
            // bootstrap-table-treetreegrid.js 插件配置 -- end
        });

        var return_top_ids = `{:input('return_top_ids')}`;
        var return_top_ids_arr = return_top_ids ? return_top_ids.split(',') : [];
        if(return_top_ids_arr.length > 0){
            return_top_ids_arr.forEach(function (val) {
                var class_name = $('.treegrid-' + val).attr('class').replace('expanded', 'collapsed');
                $('.treegrid-' + val).attr('class', class_name).find('td').eq(1).find('span').attr('class', 'treegrid-expander treegrid-expander-collapsed');
            })
        }

        var return_son_ids = `{:input('return_son_ids')}`;
        var return_son_ids_arr = return_son_ids ? return_son_ids.split(',') : [];
        if(return_son_ids_arr.length > 0){
            return_son_ids_arr.forEach(function (val){
                var class_name = $('.treegrid-' + val).attr('class').replace('expanded', 'collapsed');
                $('.treegrid-' + val).hide().attr('class', class_name)
            })
        }

        /*var id = 32;
        render('treegrid-' + id)

        function render(class_name) {
            var new_class_name = $('.' + class_name).attr('class');
            var is_have_parent = new_class_name.indexOf('treegrid-parent');
            if(is_have_parent > -1){
                // 存在上级
                var arr = new_class_name.split(' ')
                var parent_class_name = arr[1];
                if(parent_class_name){
                    var parent_list = $('.' + parent_class_name);
                    parent_list.each(function (key, val){
                        var val_class = $(val).attr('class');
                        console.log(val_class)
                        $(val).show().attr('class', val_class)
                    })
                }
            }else{

            }
        }*/

        /*var top_id = `{:input('top_id')}`;
        if(top_id){
            var class_name = $('.treegrid-' + top_id).attr('class').replace('collapsed', 'expanded');
            $('.treegrid-' + top_id).attr('class', class_name).show().find('td').eq(1).find('span').attr('class', 'treegrid-expander treegrid-expander-expanded');
        }

        var brother_ids = `{:input('brother_ids')}`;
        if (brother_ids) {
            var ids_arr = brother_ids.split(',');
            ids_arr.forEach(function (val) {
                // var class_name = $('.treegrid-' + val).attr('class').replace('collapsed', 'expanded');
                var class_name = $('.treegrid-' + val).attr('class').replace('expanded', 'collapsed');
                $('.treegrid-' + val).attr('class', class_name).show().find('td').eq(2).find('span').attr('class', 'treegrid-expander treegrid-expander-expanded');
            })
        }

        var parent_ids = `{:input('parent_ids')}`;
        if(parent_ids){
            var ids_arr = parent_ids.split(',');
            ids_arr.forEach(function (val, key) {
                var class_name = $('.treegrid-' + val).attr('class').replace('collapsed', 'expanded');
                if (key == 0) {
                    $('.treegrid-' + val).attr('class', class_name).show().find('td').eq(1).find('span').eq(key + 1).attr('class', 'treegrid-expander treegrid-expander-expanded');
                } else if (key + 1 >= ids_arr.length) {
                    // 最后一个
                    $('.treegrid-' + val).attr('class', class_name).show();
                } else {
                    // 中间
                    console.log(key)
                    $('.treegrid-' + val).attr('class', class_name).show().find('td').eq(1).find('span').eq(key + 1).attr('class', 'treegrid-expander treegrid-expander-expanded');
                }
            })
        }*/
    });

    // 格式化按钮
    function operateFormatter(value, row, index) {
        return [
            '<button type="button" class="addButton btn btn-white btn-sm" style="margin-right:15px;"><i class="iconfont icon-plus" ></i>新增子目录</button>',
            '<button type="button" class="editButton btn btn-white btn-sm" style="margin-right:15px;"><i class="iconfont icon-edit" ></i>修改</button>',
            '<button type="button" class="deleteButton btn btn-white btn-sm" style="margin-right:15px;"><i class="iconfont icon-trash" ></i>删除</button>'
        ].join('');
    }

    // 格式化类型
    function typeFormatter(value, row, index) {
        if (value === 'menu') {
            return '菜单';
        }
        if (value === 'button') {
            return '按钮';
        }
        if (value === 'api') {
            return '接口';
        }
        return '-';
    }

    // 格式化状态
    function statusFormatter(value, row, index) {
        if (value === 1) {
            return '<span class="label label-success">正常</span>';
        } else {
            return '<span class="label label-default">锁定</span>';
        }
    }

    //初始化操作按钮的方法
    window.operateEvents = {
        'click .addButton': function (e, value, row, index) {
            add(row.id);
        },
        'click .editButton': function (e, value, row, index) {
            update(row.id);
        },
        'click .deleteButton': function (e, value, row, index) {
            del(row.id);
        }
    };
</script>
<script>
    /**
     * 选中父项时，同时选中子项
     * @param datas 所有的数据
     * @param row 当前数据
     * @param id id 字段名
     * @param pid 父id字段名
     */
    function selectChilds(datas, row, id, pid, checked) {
        for (var i in datas) {
            if (datas[i][pid] == row[id]) {
                datas[i].check = checked;
                selectChilds(datas, datas[i], id, pid, checked);
            }
            ;
        }
    }

    function selectParentChecked(datas, row, id, pid) {
        for (var i in datas) {
            if (datas[i][id] == row[pid]) {
                datas[i].check = true;
                selectParentChecked(datas, datas[i], id, pid);
            }
            ;
        }
    }

    function test() {
        var selRows = $table.bootstrapTable("getSelections");
        if (selRows.length == 0) {
            alert("请至少选择一行");
            return;
        }

        var postData = "";
        $.each(selRows, function (i) {
            postData += this.id;
            if (i < selRows.length - 1) {
                postData += "， ";
            }
        });
        alert("你选中行的 id 为：" + postData);

    }

    function add(id) {
        window.location.href = '/admin/Manage/doCourseCategory/style/add/id/' + id + '.html';
    }

    function update(id) {
        window.location.href = '/admin/Manage/doCourseCategory/style/edit/id/' + id + '.html';
    }

    function del(id) {
        var msg = $(this).data('msg') ? $(this).data('msg') : '您确认删除吗？';
        var url = "{:url('delCourseCategory')}";

        swal({
            title: msg,
            type: "warning",
            cancelButtonText: '取消',
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "确认",
            closeOnConfirm: false
        }, function () {
            // 加载层
            var index = layer.load(2, {shade: [0.2, '#000']});

            $.get(url, {id}, function (res) {
                if (res.result == 1) {
                    setTimeout(function () {
                        window.location.reload();
                    }, res.timer)
                } else if (res.result == 2) {
                    layer.close(index);
                    layer.msg(res.msg);
                }
            }, 'json');

            setTimeout(function () {
                layer.close(index);
            }, 3000)
        })
    }


</script>{/block}
